package org.example.messagepack;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.example.entity.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * @author Aaron
 * @since 2020/12/17 10:31
 * <p>描述：</p>
 */
public class EchoServer {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(EchoServer.class);

    public void bind(String host, int port) throws Exception {
        final EventLoopGroup bossGroup = new NioEventLoopGroup();
        final EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            final ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast("frameEncoder", new LengthFieldPrepender(2))
                                    .addLast("encoder", new MessagePackEncoder())
                                    .addLast(new LengthFieldBasedFrameDecoder(65535,
                                            0, 2, 0, 2))
                                    .addLast("decoder", new MessagePackDecoder())
                                    .addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture f = b.bind(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class EchoServerHandler extends ChannelInboundHandlerAdapter {
        private int counter = 0;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            List<Object> uis = (List<Object>) msg;
            log.info("run counter is :{}", (++this.counter));

            for (Object ui : uis) {
                log.info("UserInfo prop = {}", ui);
            }
            ctx.writeAndFlush(uis);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.error("error=", cause);
            ctx.close();
        }
    }

    public static void main(String[] args) throws Exception {
        new EchoServer().bind("127.0.0.1", 8080);
    }

}